package com.airS.task.fileMgr.service.mgr.impl;

import com.airS.task.fileMgr.common.page.Page;
import com.airS.task.fileMgr.example.mgr.FileOperalogExample;
import com.airS.task.fileMgr.mapper.mgr.FileOperalogMapper;
import com.airS.task.fileMgr.model.mgr.FileOperalog;
import com.airS.task.fileMgr.query.mgr.FileOperalogQuery;
import com.airS.task.fileMgr.service.mgr.FileOperalogService;
import com.airS.task.fileMgr.utils.collection.CollectionUtils;
import com.airS.task.fileMgr.utils.page.PageUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * Created by alan on 2017/3/17.
 */
@Service
public class FileOperalogServiceImpl implements FileOperalogService{

    private static Logger logger = LoggerFactory.getLogger(FileOperalogServiceImpl.class);

    @Autowired
    private FileOperalogMapper fileOperalogMapper;

    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Override
    public Integer addFileOperalog(final FileOperalog fileOperalog) {
        try{
            // 异步写入DB
            threadPoolTaskExecutor.execute(new Runnable() {
                @Override
                public void run() {
                try{
                    fileOperalogMapper.insert(fileOperalog);
                }catch(Exception e){
                    logger.error("文件日志写入DB异常，请检查",e);
                }
                }
            });
        }catch(Exception e){
            logger.error("文件日志写入DB异常，请检查",e);
        }
        return null;
    }

    @Override
    public Page<FileOperalog> queryYunfiles(FileOperalogQuery query) {
        PageUtil.startPage(query);
        List<FileOperalog> fileOperalogs = fileOperalogMapper.selectByExample(assemblyFileOperalogExample(query));
        return new Page<FileOperalog>(fileOperalogs);
    }

    private FileOperalogExample assemblyFileOperalogExample(FileOperalogQuery query){
        FileOperalogExample example = new FileOperalogExample();
        FileOperalogExample.Criteria criteria = example.createCriteria();
        if(StringUtils.hasText(query.getFileName())){
            criteria.andFileNameLike("%" + query.getFileName() + "%");
        }
        if(StringUtils.hasText(query.getFileType())){
            criteria.andFileTypeEqualTo(query.getFileType());
        }
        if(StringUtils.hasText(query.getGroupName())){
            criteria.andGroupNameLike("%" + query.getGroupName() + "%");
        }
        // 默认排序，按时间倒序
        example.setOrderByClause("create_time desc");
        return example;
    }
}
